package com.xhwl.logistics.service.impl.http;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.logistics.bo.cent.VehicleParkingInfoBO;
import com.xhwl.logistics.component.SignForCheAn;
import com.xhwl.logistics.dto.http.CarInParkingLotCheAnDTO;
import com.xhwl.logistics.dto.http.CarportCheAnDTO;
import com.xhwl.logistics.dto.http.ResponseCommonCheAnDTO;
import com.xhwl.logistics.dto.http.query.QueryCarInParkingLotCheAnDTO;
import com.xhwl.logistics.dto.http.query.QueryCommonCheAnDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

@Slf4j
//@Service
public class CheAnHttpServiceImpl {

    @Autowired
    private SignForCheAn sign;

    private void cheAnResponseHandle(ResponseCommonCheAnDTO<?> responseCommonCheAnDTO) {
        if (!responseCommonCheAnDTO.getStatus()) {
            throw new BusinessException("访问车安的http接口，返回的status不是代表成功的true,错误的code: " + responseCommonCheAnDTO.getCode() + ",错误的message: " + responseCommonCheAnDTO.getMessage());
        }
    }

    public CarportCheAnDTO queryCarport(VehicleParkingInfoBO vehicleParkingInfoBO, QueryCommonCheAnDTO<Void> queryCommonCheAnDTO) {
        final String path = "/api.aspx/park.lot.status.total";

        String host = vehicleParkingInfoBO.getHost();
        String privateKey = vehicleParkingInfoBO.getAppSecret();

        String responseBodyString = HttpUtil.post(host + path, JSON.toJSONString(sign.sign(queryCommonCheAnDTO, privateKey), SerializerFeature.WriteMapNullValue));

        ResponseCommonCheAnDTO<CarportCheAnDTO> response = JSON.parseObject(responseBodyString, new TypeReference<ResponseCommonCheAnDTO<CarportCheAnDTO>>() {});
        cheAnResponseHandle(response);

        return response.getData();
    }

    public List<CarInParkingLotCheAnDTO> queryCarInParkingLot(VehicleParkingInfoBO vehicleParkingInfoBO, QueryCommonCheAnDTO<QueryCarInParkingLotCheAnDTO> queryCommonCheAnDTO) {
        final String path = "/api.aspx/park.in.info";

        String host = vehicleParkingInfoBO.getHost();
        String privateKey = vehicleParkingInfoBO.getAppSecret();

        String responseBodyString = HttpUtil.post(host + path, JSON.toJSONString(sign.sign(queryCommonCheAnDTO, privateKey), SerializerFeature.WriteMapNullValue));

        ResponseCommonCheAnDTO<List<CarInParkingLotCheAnDTO>> response = JSON.parseObject(responseBodyString, new TypeReference<ResponseCommonCheAnDTO<List<CarInParkingLotCheAnDTO>>>() {});
        cheAnResponseHandle(response);

        return response.getData();
    }

}
